package com.kinptm.masterclock.ui.fragment;

import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.google.common.collect.Lists;
import com.kinptm.masterclock.R;
import com.kinptm.masterclock.bean.AlarmNotice;
import com.kinptm.masterclock.utils.ViewUtil;

import java.io.File;
import java.io.IOException;
import java.util.List;


public class SelectAlarmNoticeFragment extends DialogFragment implements AdapterView.OnItemClickListener,
        RadioGroup.OnCheckedChangeListener, View.OnClickListener {
    private RadioGroup mSelectRadioGroup;
    private ViewFlipper mViewFlipper;
    private ListView mSystemListView;
    private ListView mLocalListView;
    private List<AlarmNotice> mSystemAlarmRangs;
    private List<AlarmNotice> mLocalAlarmRangs;
    private MediaPlayer mMediaPlayer;
    private AlarmNotice mCurrentAlarmNotice;
    private OnSelectAlarmNoticeListener mListener;

    public static SelectAlarmNoticeFragment newInstance() {
        SelectAlarmNoticeFragment fragment = new SelectAlarmNoticeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_select_alarm_notice, null);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mSelectRadioGroup = ViewUtil.findView(view, R.id.select_alarm_notice_rg);
        mViewFlipper = ViewUtil.findView(view, R.id.select_alarm_notice_vf);
        mSystemListView = ViewUtil.findView(view, R.id.select_alarm_notice_system_lv);
        mLocalListView = ViewUtil.findView(view, R.id.select_alarm_notice_local_lv);

        mSelectRadioGroup.setOnCheckedChangeListener(this);
        mSystemListView.setOnItemClickListener(this);
        mLocalListView.setOnItemClickListener(this);

        ViewUtil.findViewAndClick(view, R.id.cancel_button, this);
        ViewUtil.findViewAndClick(view, R.id.ok_button, this);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new Dialog(getActivity(), android.R.style.Theme_DeviceDefault_Light_Dialog_NoActionBar);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setLooping(true);
        showSystemNotice();
    }

    private List<AlarmNotice> findSystemAlarmRangs() {
        List<AlarmNotice> notices = Lists.newArrayList();
        notices.add(new AlarmNotice(0, "无", null));
        RingtoneManager ringtoneManager = new RingtoneManager(getActivity());
        ringtoneManager.setType(RingtoneManager.TYPE_RINGTONE);
        Cursor cursor = ringtoneManager.getCursor();
        if (cursor != null) {
            while (cursor.moveToNext()) {
                int id = cursor.getInt(RingtoneManager.ID_COLUMN_INDEX);
                String title = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX);
                String uri = cursor.getString(RingtoneManager.URI_COLUMN_INDEX);
                notices.add(new AlarmNotice(id, title, Uri.parse(uri).buildUpon().appendPath(String.valueOf(id)).build()));
            }
        }
        return notices;
    }

    private List<AlarmNotice> findLocalAlarmRangs() {
        List<AlarmNotice> notices = Lists.newArrayList();
        notices.add(new AlarmNotice(0, "无", null));
        ContentResolver resolver = getActivity().getContentResolver();
        String[] projection = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DURATION};
        String selection = String.format("%s>=?", MediaStore.Audio.Media.DURATION);
        String[] selectionArgs = {String.valueOf(30 * 1000)};

        Cursor cursor = resolver.query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, selection,
                selectionArgs, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
                String filepath = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                notices.add(new AlarmNotice(id, title, Uri.fromFile(new File(filepath))));
            }
        }
        return notices;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        AlarmNotice notice = (AlarmNotice) parent.getItemAtPosition(position);

        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
        }
        try {
            if (notice.getUri() != null) {
                mMediaPlayer.reset();
                mMediaPlayer.setDataSource(getActivity(), notice.getUri());
                mMediaPlayer.prepare();
                mMediaPlayer.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        mCurrentAlarmNotice = notice;
        if (mListener != null) {
            mListener.onSelected(notice);
        }
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.select_alarm_notice_system_rb:
                showSystemNotice();
                break;
            case R.id.select_alarm_notice_local_rb:
                showLocalNotice();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        dismiss();
    }

    private void showSystemNotice() {
        if (mSystemAlarmRangs == null) {
            mSystemAlarmRangs = findSystemAlarmRangs();
            mSystemListView.setAdapter(new AlarmNoticeAdapter(getActivity(), mSystemAlarmRangs));
        }
        mViewFlipper.setDisplayedChild(0);
    }

    private void showLocalNotice() {
        if (mLocalAlarmRangs == null) {
            mLocalAlarmRangs = findLocalAlarmRangs();
            mLocalListView.setAdapter(new AlarmNoticeAdapter(getActivity(), mLocalAlarmRangs));
        }
        mViewFlipper.setDisplayedChild(1);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
        }
        mMediaPlayer.release();
    }

    private class AlarmNoticeAdapter extends ArrayAdapter<AlarmNotice> {

        public AlarmNoticeAdapter(Context context, List<AlarmNotice> objects) {
            super(context, android.R.layout.simple_list_item_activated_1, android.R.id.text1, objects);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView text = (TextView) super.getView(position, convertView, parent);
            AlarmNotice notice = getItem(position);
            text.setText(notice.getTitle());
            return text;
        }
    }

    public interface OnSelectAlarmNoticeListener {
        void onSelected(AlarmNotice notice);
    }

    public void setOnSelectAlarmNoticeListener(OnSelectAlarmNoticeListener mListener) {
        this.mListener = mListener;
    }
}
